package xio.leetcode.java.test;

import xio.leetcode.java.base.ListNode;

/**
 * 链表工具类
 */
public class LinkedListUtils {
    /**
     * 生成链表
     *
     * @param args  链表各节点的值（按输入顺序链接）
     * @param cycle 是否有环
     * @return 链表的头节点
     */
    public static ListNode generateLinkedList(boolean cycle, int... args) {
        if (args == null || args.length == 0) {
            return null;
        }
        ListNode head = new ListNode(args[0]);
        if (args.length == 1) {
            if (cycle) {
                head.next = head;
            }
            return head;
        }
        ListNode tmp = head;
        for (int i = 1; i < args.length; i++) {
            tmp.next = new ListNode(args[i]);
            tmp = tmp.next;
        }
        if (cycle) {
            tmp.next = head;
        }
        return head;
    }

    /**
     * 生成不带环的链表
     */
    public static ListNode generateLinkedList(int... args) {
        return generateLinkedList(false, args);
    }

    /**
     * 打印链表的值
     *
     * @param head 待打印的链表的头节点
     */
    public static void printLinkedList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
    }
}
